const express = require('express')
const superagent = require('superagent')
const cheerio = require('cheerio')
var router = express.Router();
let mvname
let mvhtml = []
let mvs = []
var getMovie1 = (res) => {
    let mvss = []
    let $ = cheerio.load(res.text)
    try {
        $('ul .m1 .link-hover').each((idx, ele) => {
            if ($(ele).attr('title') && $(ele).attr('href') && $(ele).find('img').attr('data-original')) {
                let mvname = 'http://www.kk2w.cc/index.php' + $(ele).attr('href');
                let id = mvname.split('-')
                id = id[id.length - 1]
                id = id.replace('.html', '')
                let base = 'http://www.kk2w.cc/?'
                let ht = mvname.split('?')
                let http = ht[1]
                http = base + http.replace('detail', 'play')
                    // console.log(http);
                let movies = {
                    title: $(ele).attr('title'),
                    hrefs: http,
                    img: $(ele).find('img').attr('data-original'),
                    id,
                    actor: $(ele).find('.actor').eq(0).text(),
                    kind: $(ele).find('.actor').eq(1).text(),
                    scope: $(ele).find('.actor').eq(2).text(),
                    msg: $(ele).find('.other i').text()
                }
                mvss.push(movies)
            }
        })
    } catch (error) {
        console.log(error);
    }
    return mvss

}
router.get('/', function(req, res) {
    // let arr = ['http://localhost:5556'];
    // let index = arr.indexOf(req.headers.origin); // arr.includes()
    // if (index !== -1) {
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    try { // }
        mvname = req.query.name
    } catch (error) {
        console.log(errror);
    }
    var http = encodeURI(`kk2w.cc/?m=vod-search-pg-1-wd-${mvname}.html`)
    var httpdou = encodeURI(`search.douban.com/movie/subject_search?search_text=${mvname}`)
    superagent.get(http, function(err, resulst) {
        mvhtml = []
        let msg = ""
        try {
            if (!err) {
                // var str = encodeURI(res);
                mvhtml = getMovie1(resulst)
                msg = 'ok'
            }

        } catch (error) {
            console.log(error);
            msg = 'fail'
        }
        let obj = {
            msg: 'ok',
            data: mvhtml,
        }
        try {
            res.send(obj)
        } catch (error) {
            res.send('fial')
        }
    })
})

module.exports = router